import React, { useState } from "react";
import { useSelector } from 'react-redux';
import { CRow, CFormInput, CButton, CCol, CFormLabel } from '@coreui/react';

const RemoveEmployee = () => {
    const [username, setUsername] = useState('');
    const [userId, setUserId] = useState(null);
    const [message, setMessage] = useState('');
    const token = useSelector((state) => state.token);

    const handleSubmitFind = async (e) => {
        e.preventDefault();
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/find_by_username?username=${encodeURIComponent(username)}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            });
            const data = await response.json();
            if (data.username) {
                setUserId(data.id);
                setMessage(`Найден пользователь: ${data.username}`);
            } else {
                setMessage('Пользователь не найден');
            }
        } catch (error) {
            console.error("Failed to find user:", error);
            setMessage('Ошибка при поиске пользователя');
        }
    };

    const handleSubmitDelete = async (e) => {
        e.preventDefault();
        if (!userId) {
            setMessage('Пользователь не найден');
            return;
        }
        try {
            const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/users/${userId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
            });
            const data = await response.json();
            if (response.ok) {
                setMessage(data.message);
            } else {
                const data = await response.json();
                setMessage(data.message || 'Ошибка при удалении пользователя');
            }
        } catch (error) {
            console.error("Failed to delete user:", error);
            setMessage('Ошибка при удалении пользователя');
        }
    };

    return (
        <div>
            <h1>Удалить сотрудника</h1>
            <br></br>
            <form onSubmit={handleSubmitFind}>
                <CRow>
                    <CCol xs={6}>
                        <CFormInput
                            type="text"
                            placeholder="Фамилия Имя Отчество"
                            aria-label="Username"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                        />
                    </CCol>
                </CRow>
                <br></br>
                <CRow>
                    <CCol xs={3}>
                        <CButton color="light" variant="outline" type="submit">Найти</CButton>
                    </CCol>
                    <CCol xs={3}>
                        <CButton color="light" variant="outline" type="button" onClick={handleSubmitDelete}>Удалить</CButton>
                    </CCol>
                </CRow>
            </form>
            <CRow>
                <CFormLabel htmlFor="staticEmail" className="col-sm-12 col-form-label">{message}</CFormLabel>
            </CRow>
        </div>
    );
};

export default RemoveEmployee;
